import { _decorator, Asset, Component, JsonAsset, Label, Node, Prefab, ProgressBar, sys, TextAsset } from 'cc';
import ViewBase from '../../engine/ViewBase';
import VersionManager from '../../engine/VersionManager';
import { EventManager } from '../../engine/EventManager';
import HotUpdate from '../../engine/HotUpdate';
import { HttpHelper } from '../../net/HttpHelper';
import UIManager from '../../engine/UIManager';
import { ViewConfig } from '../config/ViewConfig';
import { NickNameConfig } from '../config/NickNameConfig';
import { ConfigJson } from '../config/ConfigJson';
import { Logger } from '../../engine/Logger';
import ResourcesManager from '../../engine/ResourceManager';
import { UIHelper } from '../util/UIHelper';
import GameController from '../../GameController';
const { ccclass, property } = _decorator;

@ccclass('ViewLoading')
export class ViewLoading extends ViewBase {

    @property({ type: Asset })
    private manifest: Asset = null; //本地project.manifest资源清单文件

    private lbVersion: Label;
    private progressBar: ProgressBar;
    private maxProgress: number = 0
    private lbMsg: Label

    onEnable() {
        super.onEnable();
        this.lbVersion = this.getChild(this.node, "lbVersion", Label)
        this.refreshVersion()
        this.lbMsg = this.getChild(this.node, "lbMsg", Label)
        EventManager.instance.on(HotUpdate.Event_On_NeedUpdate, this.onNeedUpdate, this);
        EventManager.instance.on(HotUpdate.Event_On_Progress, this.onUpdateProgress, this);
        EventManager.instance.on(HotUpdate.Event_On_Fail_Update, this.onUpdateFail, this);
        EventManager.instance.on(HotUpdate.Event_Finish_Update, this.onUpdateFinish, this);
        EventManager.instance.on(HotUpdate.Event_On_ALREADY_UP_TO_DATE, this.onUpdateFinish, this);
        this.progressBar = this.getChild(this.node, "progressBar", ProgressBar)
        this.progressBar.node.active = false
        this.setProgress(0)
        this.setProgressTip("")
        this.checkUpdate();
    }

    private checkUpdate() {
        if (sys.getNetworkType() != sys.NetworkType.NONE) {
            this.getHotupdateSwith();
        } else {
            this.scheduleOnce(() => {
                this.checkUpdate();
            }, 0.5)
        }
    }


    private getHotupdateSwith() {
        HttpHelper.get_jhao((isOk: boolean) => {
            if (sys.isBrowser) {
                isOk = false
            }
            this.progressBar.node!.active = isOk
            VersionManager.instance.isOpenHotUpdate = isOk;
            VersionManager.instance.init(this.manifest)
            this.setProgress(0)
            this.setProgressTip("正在准备");
            if (sys.isNative && VersionManager.instance.isOpenHotUpdate) {
                VersionManager.instance.checkUpdate(0);
            } else {
                this.startLoadingLocal();
            }
        })
    }

    private onNeedUpdate(key: string) {
        Logger.log("onNeedUpdate=====", key, VersionManager.Config_Key);
        if (key == VersionManager.Config_Key[0]) {
            VersionManager.instance.startUpdate(0);
            this.setProgress(0)
            this.setProgressTip("需要更新文件");
        }
    }

    private onUpdateProgress(loadedFiles: number, totalFiles: number, key: string) {
        if (key == VersionManager.Config_Key[0]) {
            let progress: number = loadedFiles / totalFiles;
            if (progress > this.maxProgress) {
                this.maxProgress = progress
                this.setProgress(this.maxProgress)
            }
            let hadLoadMb: string = (loadedFiles / 1024 / 1024).toFixed(2) + "Mb";
            let totalMb: string = (totalFiles / 1024 / 1024).toFixed(2) + "Mb";
            this.setProgressTip("正在认真更新文件 " + (this.maxProgress * 100).toFixed(2) + "%(" + hadLoadMb + "/" + totalMb + ")");
        }
    }

    private onUpdateFail(key: string) {
        if (key == VersionManager.Config_Key[0]) {
            Logger.warn("热更新失败========");
            UIHelper.showTip("热更新下载资源失败!");
            this.scheduleOnce(() => {
                GameController.instance.restartGame()
            }, 1.5)
        }
    }

    private onUpdateFinish(key: string, needRestart: boolean) {
        Logger.log("onUpdateFinish=====main===", key, needRestart);
        if (key == VersionManager.Config_Key[0] && !needRestart) {
            this.startLoadingLocal();
        }
    }

    private refreshVersion() {
        this.lbVersion.string = VersionManager.instance.getVersion()
    }

    private setProgress(progress: number) {
        if (this.progressBar) {
            this.progressBar.progress = progress;
        }
    }

    private setProgressTip(msg: string) {
        this.lbMsg.string = msg;
    }

    // 加载本地文件
    private async startLoadingLocal() {
        this.progressBar.node.active = true
        UIManager.instance.showLoadingIcon()
        let urlList: Array<string> = ViewConfig.getMustLoadList();
        // urlList.push(NickNameConfig.Res_Path);
        // let jsonList:Array<string> = []
        urlList = urlList.concat(ConfigJson.jsonList)
        // urlList = urlList.concat(AudioConfig.audioConfig.concat())
        Logger.log("startLoadingLocal", urlList)
        this.maxProgress = 0
        ResourcesManager.instance.load(urlList, (completedCount: number, totalCount: number, item: any) => {
            let progress: number = completedCount / totalCount
            if (progress > this.maxProgress) {
                this.maxProgress = progress
                this.setProgress(this.maxProgress)
                this.setProgressTip("正在认真加载本地资源 " + (this.maxProgress * 100).toFixed(2) + "% ");
            }
        }, (resource: any[]) => {
            // Logger.log("startLoadingLocal==", resource);
            // this.progressBar.parent!.active = false
            this.setProgress(1)
            this.setProgressTip("加载本地资源完成 ");
            UIManager.instance.hideLoadingIcon()
            this.initResource(resource)
            this.initPreLoadList()
            this.initLogin();
        })
    }

    private initResource(resource: any[]) {
        for (let i = 0; i < resource.length; i++) {
            if (resource[i] instanceof TextAsset) {
                this.initTxtConfig(resource[i]);
            }
            else if (resource[i] instanceof Prefab) {
                this.initPrefab(resource[i])
            }
            else if (resource[i] instanceof JsonAsset) {
                this.initJson(resource[i])
            }
        }
    }

    private initTxtConfig(resource: TextAsset) {
        if (resource.name == NickNameConfig.Config_Name) {
            NickNameConfig.resource2Config(resource)
        }
    }

    private initPrefab(prefab: Prefab) {
        // // Logger.log("initPrefab=", prefab.name, prefab)
        // if (prefab.name == PokerPrefab.PREFAB_NAME) {
        //     PokerPrefab.initPool(prefab);
        // }
        // else if (prefab.name == MjPrefab.PREFAB_NAME) {
        //     MjPrefab.initPool(prefab)
        // }
    }

    private initJson(resource: JsonAsset) {
        Logger.log("initJson=", resource.name, resource)
        ConfigJson.initJson(resource)
        // if(resource.name == Config_word.NAME){
        //     Config_word.json2Object(resource.json)
        // }

    }

    private initPreLoadList() {
        let preList: Array<string> = ViewConfig.getPreLoadList()
        preList.push(NickNameConfig.Res_Path);
        ResourcesManager.instance.load(preList, (completedCount: number, totalCount: number, item: any) => {

        }, (resource: any[]) => {
            this.setProgress(1)
            // this.setProgressTip("加载本地资源完成 ");
            UIManager.instance.hideLoadingIcon()
            // Logger.log("预加载完成=", resource)
            this.initResource(resource)
        })
    }

    private initLogin() {
        // Logger.log("加载本地文件成功")
        // AccountModel.instance.init()
        // AccountModel.instance.account = "o9glZ6DKYb7AjIz_bKHQY36I6jQM"
        // AccountModel.instance.sign = "f4b5548ae13a212656df59c540a949bb"
        // if (AccountModel.instance.account != "" && AccountModel.instance.sign != "") {
        //     SocketClient.login(true)
        // }
        // else {
        UIManager.instance.showView(ViewConfig.viewConfig.ViewAccount, () => {
            this.closeView()
        })
        // }
    }


}


